package malagaAcoge.controller.beans;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;

import malagaAcoge.utils.Messages;

public class InformesBean {
	private String path;
	private List<String> demandas;
	private List<String> usuarios;

	public InformesBean() {

	}

	public void descargarArchivo() {
		String ruta = Messages.getString("InformesBean.directorio") + path;
		File file = new File(ruta);
		if (file.exists()) {
			try {
				FacesContext facesContext = FacesContext.getCurrentInstance();
				HttpServletResponse response = (HttpServletResponse) facesContext
						.getExternalContext().getResponse();
				String contentDispositionValue = "attachment";
				response.setContentType("application/octet-strem");
				response.setHeader("Content-Disposition",
						contentDispositionValue + ";filename=\"" + path
								+ "\"");
				byte[] buffer = new byte[2048];
				int length;
				InputStream inputStream = new FileInputStream(file);
				OutputStream outputStream = response.getOutputStream();

				while ((length = (inputStream.read(buffer))) != -1) {
					outputStream.write(buffer, 0, length);
				}

				response.setStatus(200);

				response.getOutputStream().flush();
				inputStream.close();
				facesContext.responseComplete();
			} catch (IOException e) {
				System.out.println("Error al descargar el archivo: " + ruta);
			}
		}
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public List<String> getDemandas() {
		demandas = new ArrayList<String>();
		File dir = new File(Messages.getString("InformesBean.directorio"));
		String[] ficheros = dir.list();
		if (ficheros != null) {
			for (int i = 0; i < ficheros.length; i++) {
				if (ficheros[i].startsWith("Demandas")) {
					demandas.add(ficheros[i]);
				}
			}
		}

		return demandas;
	}

	public void setDemandas(List<String> demandas) {
		this.demandas = demandas;
	}

	public List<String> getUsuarios() {
		usuarios = new ArrayList<String>();
		File dir = new File(Messages.getString("InformesBean.directorio"));
		String[] ficheros = dir.list();
		if (ficheros != null) {
			for (int i = 0; i < ficheros.length; i++) {
				if (ficheros[i].startsWith("Usuarios")) {
					usuarios.add(ficheros[i]);
				}
			}
		}
		return usuarios;
	}

	public void setUsuarios(List<String> usuarios) {
		this.usuarios = usuarios;
	}

}
